package com.lucky.ebidding.controller;

import com.lucky.ebidding.model.User;
import com.lucky.ebidding.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

/**
 * ClassName:loginController
 * Package:com.lucky.ebidding.controller
 * Description:
 *
 * @Date:2020/3/14 13:44
 * @Author:857251389@qq.com
 */
@Controller
public class LoginController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param account
     * @param password
     * @param response
     * @param model
     * @return
     */
    @PostMapping("/loginJump")
    public String login(@RequestParam(name = "account") String account,
                        @RequestParam(name = "password") String password,
                        HttpServletResponse response,
                        Model model) {

        User user = userService.login(account, password);

        if (user != null) {
            String token = UUID.randomUUID().toString().replace("-", "");
            Cookie cookie = new Cookie("token", account + '_' + token);
            cookie.setMaxAge(15);
            cookie.setPath("/");
            response.addCookie(cookie);

            if(user.getStatus()==3){

                model.addAttribute("user",user);
                return "admin/admin_bam";

            }
            if(user.getStatus()==4){

                model.addAttribute("user",user);
                return "adminSh/admin1_bam";

            }
            return "redirect:/";
        }

        model.addAttribute("msg","登录失败！请检查账号或密码");
        return "login";

    }

    /**
     * 登陆跳转
     * @return
     */
    @GetMapping("/login")
    public String loginJump() {
        return "login";
    }

    /**
     * 注册跳转
     * @return
     */
    @GetMapping("/registerJump")
    public String registerJump() {
        return "register";
    }

    /**
     * 注册
     * @param user
     * @param model
     * @return
     */
    @PostMapping("/register")
    public String register(User user, Model model) {

        boolean flag = userService.register(user);
        if (!flag) {

        }
        model.addAttribute("account", user.getAccount());
        return "login";
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @return
     */
    @GetMapping("/logout")
    public String logout(HttpServletRequest request,
                     HttpServletResponse response){
    request.getSession().removeAttribute("user");
    Cookie cookie = new Cookie("token",null);
    cookie.setMaxAge(0);
    response.addCookie(cookie);
    return "redirect:/";
}

}
